package org.jeecgframework.web.controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.Port.Info;

import com.mybatis.ext.WiseCoreService;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsBkCertificatesServiceI;
import org.jeecgframework.web.service.impl.ZyInspectionPlanServiceImpl;
import org.jeecgframework.web.system.pojo.base.CbsBkCertificatesEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 巴可大学证书管理
 * @author onlineGenerator
 * @date 2016-08-01 11:09:42
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsBkCertificatesController")
public class CbsBkCertificatesController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsBkCertificatesController.class);

	@Autowired
	private CbsBkCertificatesServiceI cbsBkCertificatesService;
	@Autowired
	private SystemService systemService;

    @Autowired
    private WiseCoreService wiseCoreService;

	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 巴可大学证书管理列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsBkCertificates")
	public ModelAndView cbsBkCertificates(HttpServletRequest request) {
		return new ModelAndView("com/app/cbs_bk_certificates/cbsBkCertificatesList");
	}
    
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CbsBkCertificatesEntity cbsBkCertificates,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(CbsBkCertificatesEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsBkCertificates, request.getParameterMap());
		try{
			//自定义追加查询条件
			String query_overDate_begin = request.getParameter("overDate_begin");
			String query_overDate_end = request.getParameter("overDate_end");
			if(StringUtil.isNotEmpty(query_overDate_begin)){
				cq.ge("overDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_overDate_begin));
			}
			if(StringUtil.isNotEmpty(query_overDate_end)){
				cq.le("overDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_overDate_end));
			}
			cq.add(Restrictions.eq("isDelete", "0"));
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.cbsBkCertificatesService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 巴可大学证书管理新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CbsBkCertificatesEntity cbsBkCertificates, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsBkCertificates.getId())) {
			cbsBkCertificates = cbsBkCertificatesService.getEntity(CbsBkCertificatesEntity.class, cbsBkCertificates.getId());
			req.setAttribute("cbsBkCertificatesPage", cbsBkCertificates);
		}
		return new ModelAndView("com/app/cbs_bk_certificates/cbsBkCertificates-add");
	}
	/**
	 * @author lishuai
	 * 2016年8月26日 上午10:09:06
	 * Description  巴可大学证书号唯一性验证
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping(params="getbkcertificatesbycertificateNum")
	@ResponseBody
	public Map<String, Object> getbkcertificatesbycertificateNum(HttpServletRequest request,String param){
    	Map<String, Object> map = new HashMap<String, Object>();
    	StringBuffer sb= new StringBuffer("from CbsBkCertificatesEntity where certificateNum = ?");
    	if(StringUtil.isNotEmpty(param)){
    		List<CbsBkCertificatesEntity> info=systemService.findHql(sb.toString(), param);
    		if(info.size()>0){
    			map.put("info", "证书号已存在");
    			map.put("status","n" );
    		}else{
    			map.put("info", "验证通过");
    			map.put("status", "y");
    		}
    	}
    	
    	return map;
    }
	/**
	 * @author lishuai
	 * 2016年8月26日 下午3:47:58
	 * Description 巴可大学证书身份证唯一性验证
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping(params="getbkcertificatesbyidNum")
	@ResponseBody
	public Map<String, Object> getbkcertificatesbyidNum(HttpServletRequest request,String param){
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuffer sb= new StringBuffer("from CbsBkCertificatesEntity where  idNum = ?");
		List<CbsBkCertificatesEntity> info=systemService.findHql(sb.toString(), param);
		if(info.size()>0){
			map.put("info","身份证号已存在");
			map.put("status", "n");
		}else{
			map.put("info", "验证通过");
			map.put("status", "y");
		}
		return map;
	}
	/**
	 * 添加巴可大学证书管理
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CbsBkCertificatesEntity cbsBkCertificates, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "巴可大学证书管理添加成功";
		try{
			cbsBkCertificatesService.save(cbsBkCertificates);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "巴可大学证书管理添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 巴可大学证书管理编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(CbsBkCertificatesEntity cbsBkCertificates, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsBkCertificates.getId())) {
			cbsBkCertificates = cbsBkCertificatesService.getEntity(CbsBkCertificatesEntity.class, cbsBkCertificates.getId());
			req.setAttribute("cbsBkCertificatesPage", cbsBkCertificates);
		}
		return new ModelAndView("com/app/cbs_bk_certificates/cbsBkCertificates-update");
	}
	
	/**
	 * 更新巴可大学证书管理
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(CbsBkCertificatesEntity cbsBkCertificates, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "巴可大学证书管理更新成功";
		CbsBkCertificatesEntity t = cbsBkCertificatesService.get(CbsBkCertificatesEntity.class, cbsBkCertificates.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(cbsBkCertificates, t);
			cbsBkCertificatesService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "巴可大学证书管理更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * @author lishuai
	 * 2016年8月26日 下午3:48:38
	 * Description 巴可大学证书逻辑删除
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "logicDelete")
	@ResponseBody
	public AjaxJson logicDelete(String id, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "";
		try {
			CbsBkCertificatesEntity t = cbsBkCertificatesService.get(CbsBkCertificatesEntity.class, id);
			if("0".equals(t.getIsDelete())){
				t.setIsDelete("1");
			}
			message=t.getName()+"已删除";
			cbsBkCertificatesService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message="删除失败";
		}
		j.setMsg(message);
		return j;
	}

	
	/**
	 * 删除巴可大学证书管理
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CbsBkCertificatesEntity cbsBkCertificates, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cbsBkCertificates = systemService.getEntity(CbsBkCertificatesEntity.class, cbsBkCertificates.getId());
		message = "巴可大学证书管理删除成功";
		try{
			cbsBkCertificatesService.delete(cbsBkCertificates);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "巴可大学证书管理删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除巴可大学证书管理
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "巴可大学证书管理删除成功";
		try{
			for(String id:ids.split(",")){
				CbsBkCertificatesEntity cbsBkCertificates = systemService.getEntity(CbsBkCertificatesEntity.class, 
				id
				);
				cbsBkCertificatesService.delete(cbsBkCertificates);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "巴可大学证书管理删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 导入功能跳转
	 * @return
	 */
	@RequestMapping(params = "uploadBkCertificate")
	public ModelAndView uploadBkCertificate(HttpServletRequest req) {
		return new ModelAndView("com/app/cbs_bk_certificates/uploadBkCertificate");
	}
	
	/**
	 * @Description 解析EXCEL并保存
	 */
	@ResponseBody
	@RequestMapping(params = "importExcel")
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		message = "上传成功";
		try {
			long begin = System.currentTimeMillis();
			cbsBkCertificatesService.parseExcel(request);
			long end = System.currentTimeMillis();
			System.out.println("解析EXCEL巴可证书管理并保存  用时："+(end - begin) / 1000 +"." + (end - begin) % 1000 +"秒");
		} catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			message = "上传失败";
		}
		j.setMsg(message);
		return j;
	}

    /**
     * 导出excel 模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public void exportXlsByT(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        try {
            @SuppressWarnings("deprecation")
            String templatePath = request.getRealPath("/") + "export/template/certification.xlsx";
            FileUtils.downFile(templatePath, "巴可大学证书模板.xlsx", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(params = "export")
    @ResponseBody
    public void export(CbsBkCertificatesEntity certificate,HttpServletRequest request,HttpServletResponse response){
        String hql = "from CbsBkCertificatesEntity where 1=1 and isDelete=0 ";
        if(!StringUtil.isEmpty(certificate.getName())){
            hql += " and name like '%"+certificate.getName()+"%'";
        }
        if(!StringUtil.isEmpty(certificate.getIdNum())){
            hql += " and idNum like '%"+certificate.getIdNum()+"%'";
        }
        hql += " order by createDate desc";
        List<CbsBkCertificatesEntity> certificates = cbsBkCertificatesService.findHql(hql);
        exportCertificate(certificates,request,response);

    }

    public void exportCertificate(List<CbsBkCertificatesEntity> certificates,HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;
        try {
            String fileName = "巴可大学证书.xlsx";
            response.setCharacterEncoding("text/html;charset=utf-8");
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + (new String(fileName.getBytes("gb2312"), "ISO8859-1")));
            out = response.getOutputStream();
            InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader().getResourceAsStream("jeecg/template/certification.xlsx");
            XSSFWorkbook xssf = new XSSFWorkbook(is);
            XSSFSheet sheet = xssf.getSheetAt(0);
            int rowNum = 1;
            for (CbsBkCertificatesEntity certificate : certificates) {
                XSSFRow row = sheet.createRow(rowNum);
                XSSFCell cellName = row.createCell(0);
                cellName.setCellValue(oConvertUtils.getString(certificate.getName()));
                XSSFCell cellcertifiCcateNum = row.createCell(1);
                cellcertifiCcateNum.setCellValue(oConvertUtils.getString(certificate.getCertificateNum()));
                XSSFCell cellOverDate = row.createCell(2);
                if(certificate.getOverDate() != null){
                    cellOverDate.setCellValue(certificate.getOverDate());
                }
                XSSFCell cellCourseNum = row.createCell(3);
                cellCourseNum.setCellValue(oConvertUtils.getString(certificate.getCourseNum()));
                XSSFCell cellIdNum = row.createCell(4);
                cellIdNum.setCellValue(oConvertUtils.getString(certificate.getIdNum()));
                rowNum++;
            }
            xssf.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
